# -*- coding: utf-8 -*- 

###########################################################################
## Python code generated with wxFormBuilder (version Aug 23 2015)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################

import wx
import wx.xrc

import ConfigModule as cm
import SvnUtillity as su


###########################################################################
# Class WxChangePathEvent
###########################################################################
class WxChangePathEvent(wx.PyCommandEvent):

    def __init__(self, evt_type, id):
        wx.PyCommandEvent.__init__(self, evt_type, id)
        self.new_prj = ''

    def get_new_prj(self):
        return self.new_prj

    def set_new_prj(self, new_prj):
        self.new_prj = new_prj

# region 事件定义
CHANGE_PATH_EVENT_TYPE = wx.NewEventType()
EVT_CHANGE_PATH = wx.PyEventBinder(CHANGE_PATH_EVENT_TYPE, 1)


###########################################################################
# Class WxEditPrjConfigEvent
###########################################################################
class WxEditPrjConfigEvent(wx.PyCommandEvent):

    def __init__(self, evt_type, id):
        wx.PyCommandEvent.__init__(self, evt_type, id)
        self.prj_name = ''

    def set_prj_name(self, prj_name):
        self.prj_name = prj_name

    def get_prj_name(self):
        return self.prj_name

EDIT_PRJ_EVENT_TYPE = wx.NewEventType()
EVT_EDIT_PRJ_CONFIG = wx.PyEventBinder(EDIT_PRJ_EVENT_TYPE, 1)
# endregion 事件定义


###########################################################################
# Class ProjectEditPanel
###########################################################################
class ProjectEditPanel(wx.Panel):

    def __init__(self, parent, *args, **kwargs):

        is_edit_mode = kwargs.get('mode') == 'add' or False
        prj_list = kwargs.get('prj_list') or []

        sub_args = [arg for arg in args if arg != 'mode' and arg != 'prj_list']
        sub_kwargs = {k: v for k, v in kwargs.items() if k != 'mode' and k != 'prj_list'}
        wx.Panel.__init__(self, parent, *sub_args, **sub_kwargs)

        self.prj_list = prj_list
        self.parent = parent
        prj_v_sizer = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, u'项目信息'), wx.VERTICAL)

        self.prj_panel = wx.Panel(prj_v_sizer.GetStaticBox(), wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
                                  wx.TAB_TRAVERSAL)
        base_v_sizer = wx.BoxSizer(wx.VERTICAL)

        prj_h_sizer = wx.BoxSizer(wx.HORIZONTAL)

        self.m_staticText5 = wx.StaticText(self.prj_panel, wx.ID_ANY, u'项目名称', wx.DefaultPosition, wx.Size(60, -1), 0)
        self.m_staticText5.Wrap(-1)
        prj_h_sizer.Add(self.m_staticText5, 0, wx.ALL, 5)

        self.prjText = wx.TextCtrl(self.prj_panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)
        self.prjText.Enable(is_edit_mode)
        prj_h_sizer.Add(self.prjText, 0, wx.ALL, 5)

        self.m_panel3 = wx.Panel(self.prj_panel, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL)
        prj_h_sizer.Add(self.m_panel3, 1, wx.EXPAND | wx.ALL, 5)

        base_v_sizer.Add(prj_h_sizer, 1, wx.EXPAND, 5)

        path_h_sizer = wx.BoxSizer(wx.HORIZONTAL)

        self.pathStaticText = wx.StaticText(self.prj_panel, wx.ID_ANY, u'本地路径', wx.DefaultPosition, wx.Size(60, -1), 0)
        self.pathStaticText.Wrap(-1)
        path_h_sizer.Add(self.pathStaticText, 0, wx.ALL, 5)

        self.pathText = wx.TextCtrl(self.prj_panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(300, -1), 0)
        self.pathText.Enable(False)

        path_h_sizer.Add(self.pathText, 0, wx.ALL, 5)

        self.btnBrowse = wx.Button(self.prj_panel, wx.ID_ANY, u'浏览', wx.DefaultPosition, wx.DefaultSize, 0)
        path_h_sizer.Add(self.btnBrowse, 0, wx.ALL, 5)

        base_v_sizer.Add(path_h_sizer, 1, wx.EXPAND, 0)

        rep_v_sizer = wx.BoxSizer(wx.VERTICAL)

        url_h_sizer = wx.BoxSizer(wx.HORIZONTAL)

        self.urlSText = wx.StaticText(self.prj_panel, wx.ID_ANY, u'库地址', wx.DefaultPosition, wx.Size(60, -1), 0)
        self.urlSText.Wrap(-1)
        url_h_sizer.Add(self.urlSText, 0, wx.ALL, 5)

        self.urlText = wx.TextCtrl(self.prj_panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.Size(300, -1), 0)
        url_h_sizer.Add(self.urlText, 0, wx.ALL, 5)

        rep_v_sizer.Add(url_h_sizer, 1, wx.EXPAND, 0)

        usr_h_sizer = wx.BoxSizer(wx.HORIZONTAL)

        self.usrSText = wx.StaticText(self.prj_panel, wx.ID_ANY, u'用户名', wx.DefaultPosition, wx.Size(60, -1), 0)
        self.usrSText.Wrap(-1)
        usr_h_sizer.Add(self.usrSText, 0, wx.ALL, 5)

        self.usrText = wx.TextCtrl(self.prj_panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)
        usr_h_sizer.Add(self.usrText, 0, wx.ALL, 5)

        self.pwdSText = wx.StaticText(self.prj_panel, wx.ID_ANY, u'密码', wx.DefaultPosition, wx.Size(60, -1), 0)
        self.pwdSText.Wrap(-1)
        usr_h_sizer.Add(self.pwdSText, 0, wx.ALL, 5)

        self.pwdText = wx.TextCtrl(self.prj_panel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0)
        usr_h_sizer.Add(self.pwdText, 0, wx.ALL, 5)

        rep_v_sizer.Add(usr_h_sizer, 1, wx.EXPAND, 0)

        base_v_sizer.Add(rep_v_sizer, 1, wx.EXPAND, 0)

        self.btnSave = wx.Button(self.prj_panel, wx.ID_ANY, u'保存', wx.DefaultPosition, wx.DefaultSize, 0)
        base_v_sizer.Add(self.btnSave, 0, wx.ALL, 5)

        self.prj_panel.SetSizer(base_v_sizer)
        self.prj_panel.Layout()
        base_v_sizer.Fit(self.prj_panel)
        prj_v_sizer.Add(self.prj_panel, 1, wx.EXPAND | wx.ALL, 5)

        self.SetSizer(prj_v_sizer)
        self.Layout()

        self.Centre(wx.BOTH)

        # Connect Events
        self.btnSave.Bind(wx.EVT_BUTTON, self.on_save)
        self.btnBrowse.Bind(wx.EVT_BUTTON, self.on_browse)

        self.prj_config = None

    def on_save(self, evt):
        # wx.MessageBox('%s, %s, %s, %s, %s' % (self.prjText.GetValue(), self.urlText.GetValue(),
        #                                       self.usrText.GetValue(), self.pwdText.GetValue(),
        #                                       self.pathText.GetValue()))
        prj_name = self.prjText.GetValue()
        overwrite_flg = True
        if prj_name in self.prj_list:
            dlg = wx.MessageDialog(self,
                                   u'''保存的项目名称已经存在了,可能会被覆盖,要继续吗?''',
                                   u'警告',
                                   wx.YES_NO | wx.ICON_QUESTION
                                   )
            rlt = dlg.ShowModal()
            if rlt == wx.ID_YES:
                overwrite_flg = True
            else:
                overwrite_flg = False
            dlg.Destroy()

        if overwrite_flg:
            self.prj_config = cm.Project(prj_name, self.urlText.GetValue(), self.usrText.GetValue(),
                                         self.pwdText.GetValue(), self.pathText.GetValue())

        self.parent.EndModal(wx.ID_OK)

    def get_prj_config(self):
        return self.prj_config

    def on_browse(self, evt):
        path = wx.DirDialog(None, message=u'请选择路径', defaultPath=self.pathText.GetValue() or u'',
                            style=wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST)
        result = path.ShowModal()
        if result == wx.ID_OK:
            self.pathText.SetValue(path.GetPath())

    def set_config(self, name, config):
        self.prjText.SetValue(name)
        self.urlText.SetValue(config.get(u'repository').get(u'url'))
        self.usrText.SetValue(config.get(u'repository').get(u'user'))
        self.pwdText.SetValue(config.get(u'repository').get(u'password'))
        self.pathText.SetValue(config.get(u'local'))


###########################################################################
# Class ProjectEditDialog
###########################################################################
class ProjectEditDialog(wx.Dialog):

    def __init__(self, parent, config_parser, mode='edit'):
        size = wx.Size(500, 240)

        if 'wxMSW' in wx.PlatformInfo:
            size = wx.Size(500, 280)

        wx.Dialog.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition,
                           size=size, style=wx.DEFAULT_DIALOG_STYLE | wx.DIALOG_EX_METAL)
        self.SetSizeHintsSz(size, size)
        prj_list = config_parser.get_project_list()
        self.prj_panel = ProjectEditPanel(self, mode=mode, prj_list=prj_list)

    def set_config(self, name, config):
        self.prj_panel.set_config(name, config)

    def get_prj_config(self):
        return self.prj_panel.get_prj_config()


###########################################################################
# Class PrjPanel
###########################################################################
class PrjPanel(wx.Panel):

    def __init__(self, *args, **kwargs):

        self.config_parser = kwargs.get('config_parser')
        sub_args = [arg for arg in args if arg != 'config_parser']
        sub_kwargs = {k: v for k, v in kwargs.items() if k != 'config_parser'}

        wx.Panel.__init__(self, *sub_args, **sub_kwargs)
        self.sizer = wx.BoxSizer(wx.VERTICAL)

        self.sizer.Fit(self)
        self.prj_list_box = listbox = wx.CheckListBox(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, [], 0)
        self.add_btn = add_btn = wx.Button(self, id=wx.ID_ANY, label='+', pos=wx.DefaultPosition,
                                           size=wx.Size(24, 24), style=wx.BU_EXACTFIT)
        self.rmv_btn = rmv_btn = wx.Button(self, id=wx.ID_ANY, label='-', pos=wx.DefaultPosition,
                                           size=wx.Size(24, 24), style=wx.BU_EXACTFIT)

        self.co_btn = co_btn = wx.Button(self, id=wx.ID_ANY, label=u'↓', pos=wx.DefaultPosition,
                                         size=wx.Size(24, 24), style=wx.BU_EXACTFIT)

        h_sizer = wx.BoxSizer(wx.HORIZONTAL)

        self.sizer.Add(self.prj_list_box, 1, wx.EXPAND)
        self.sizer.Add(h_sizer, 0, wx.EXPAND)
        h_sizer.Add(add_btn, 0, wx.SHAPED)
        h_sizer.Add(rmv_btn, 0, wx.SHAPED)
        h_sizer.Add(co_btn, 0, wx.SHAPED)
        self.SetSizer(self.sizer)

        # init status
        rmv_btn.Enable(False)
        co_btn.Enable(False)

        # event connections
        listbox.Bind(wx.EVT_LISTBOX, self.on_prj_change)
        listbox.Bind(wx.EVT_LISTBOX_DCLICK, self.on_prj_dbclick)
        listbox.Bind(wx.EVT_CHECKLISTBOX, self.on_prj_checked)
        # 捕获uichange事件弥补没有deselect事件
        listbox.Bind(wx.EVT_UPDATE_UI, self.on_prj_deselect)

        rmv_btn.Bind(wx.EVT_BUTTON, self.on_rmv_clicked)
        add_btn.Bind(wx.EVT_BUTTON, self.on_add_clicked)
        # co_btn.Bind(wx.EVT_BUTTON, self.on_co_clicked)

    # 捕获uichange事件弥补没有deselect事件
    def on_prj_deselect(self, event):
        list_box = self.prj_list_box
        selection = list_box.GetSelection()
        if -1 == selection:
            self.co_btn.Enable(False)

    def add_prj(self, prj_name):
        list_box = self.prj_list_box
        if list_box.FindString(prj_name) == wx.NOT_FOUND:
            list_box.Append(prj_name)

    def set_prj_list(self, prj_list):
        self.prj_list_box.AppendItems(prj_list)

    def on_prj_change(self, event):
        list_box = self.prj_list_box
        selection = list_box.GetSelection()
        label = list_box.GetString(selection)
        # 判断co button的可用状态
        cfg_dic = self.config_parser.get_prj_config(label)
        path = cfg_dic['local']

        self.co_btn.Enable(su.is_svn_path(path))

        # 发送项目变化消息
        evt = WxChangePathEvent(CHANGE_PATH_EVENT_TYPE, self.GetId())
        evt.set_new_prj(label)
        self.GetEventHandler().ProcessEvent(evt)

    def on_prj_dbclick(self, event):
        list_box = self.prj_list_box
        selection = list_box.GetSelection()
        label = list_box.GetString(selection)
        # 发送项目编辑消息
        evt = WxEditPrjConfigEvent(EDIT_PRJ_EVENT_TYPE, self.GetId())
        evt.set_prj_name(label)
        self.GetEventHandler().ProcessEvent(evt)

    def on_rmv_clicked(self, event):
        name_list = self.prj_list_box.GetCheckedStrings()
        dlg = wx.MessageDialog(self,
                               u'确认要删除项目(%s)吗?' % ','.join(name_list),
                               u'警告',
                               wx.YES_NO | wx.ICON_QUESTION
                               )
        rlt = dlg.ShowModal()

        if rlt == wx.ID_YES:
            for name in name_list:
                self.config_parser.del_prj_config(name)
                list_box = self.prj_list_box
                list_box.Delete(list_box.FindString(name))
            self.config_parser.persist_config()

        dlg.Destroy()

    def on_add_clicked(self, event):
        dlg = ProjectEditDialog(self, self.config_parser, mode='add')
        rst = dlg.ShowModal()
        if rst == wx.ID_OK:
            config = dlg.get_prj_config()
            self.add_prj(config.name)
            self.config_parser.merge_config(config)
            self.config_parser.persist_config()

    def on_prj_checked(self, event):
        btn = self.rmv_btn
        lst = self.prj_list_box.GetCheckedStrings()

        btn.Enable(len(lst) > 0)


# test code
class ProjectFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition,
                          size=wx.Size(500, 240), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)

        self.SetSizeHintsSz(wx.Size(500, 240), wx.Size(500, 240))

        self.panel = PrjPanel(self)

    def get_frame(self):
        return self.frame


if __name__ == '__main__':
    app = wx.App()
    frame = ProjectFrame(None)
    frame.panel.set_prj_list(['a', 'b', 'c'])
    app.SetTopWindow(frame)
    frame.Show()
    app.MainLoop()
